{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0",
   "metadata": {},
   "source": [
    "# Instances and ports\n",
    "\n",
    "Gdsfactory defines your component once in memory and can add multiple Instances (references) to the same component."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1",
   "metadata": {},
   "source": [
    "As you build components, you can include references to other components. Adding an instance is like having a pointer to a component.\n",
    "\n",
    "The GDSII specification allows the use of instances, and similarly gdsfactory uses them (with the `add_ref()` function).\n",
    "what is an instance? Simply put:  **An instance does not contain any geometry. It only *points* to an existing geometry**.\n",
    "\n",
    "Say you have a ridiculously large polygon with 100 billion vertices that you call BigPolygon. It is huge, and you need to use it in your design 250 times.\n",
    "Well, a single copy of BigPolygon takes up 1MB of memory, so you do not want to make 250 copies of it\n",
    "You can instead *instantiate* the polygon 250 times.\n",
    "Each instance only uses a few bytes of memory -- it only needs to know the memory address of BigPolygon, position, rotation and mirror.\n",
    "This way, you can keep one copy of BigPolygon and use it again and again.\n",
    "\n",
    "You can start by making a blank `Component` and add a single polygon to it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "# Create a blank Component\n",
    "p = gf.Component()\n",
    "\n",
    "# Add a polygon.\n",
    "xpts = [0, 0, 5, 6, 9, 12]\n",
    "ypts = [0, 1, 1, 2, 2, 0]\n",
    "# The zip function takes two lists (xpts and ypts) and pairs their elements together. \n",
    "# The first element of xpts is paired with the first of ypts, the second with the second, and so on.\n",
    "# This creates a sequence of (x, y) tuples. A tuple is a data structure that consists of multiple parts.\n",
    "# list(...): The output of zip is converted into a list of these coordinate tuples.\n",
    "p.add_polygon(list(zip(xpts, ypts)), layer=(2, 0))\n",
    "\n",
    "# Plot the Component with the polygon in it.\n",
    "p.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3",
   "metadata": {},
   "source": [
    "Now, you want to reuse this polygon repeatedly without creating multiple copies of it.\n",
    "\n",
    "To do so, you need to make a second blank `Component`, this time called `c`.\n",
    "\n",
    "In this new Component you *instantiate* our Component `p` which contains our polygon."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()  # Create a new blank component.\n",
    "poly_ref = c.add_ref(p)  # instantiate the component \"p\" that has the polygon in it.\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5",
   "metadata": {},
   "source": [
    "You just made a copy of your polygon -- but remember, you did not actually\n",
    "make a second polygon, you just made a reference (aka pointer) to the original\n",
    "polygon.  Let us add two more references to `c`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6",
   "metadata": {},
   "outputs": [],
   "source": [
    "poly_ref2 = c.add_ref(p) \n",
    "poly_ref3 = c.add_ref(p)  \n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7",
   "metadata": {},
   "source": [
    "Now you have 3x polygons all on top of each other.  Again, this would appear\n",
    "useless, except that you can manipulate each instance independently. Notice that\n",
    "when you called `c.add_ref(p)` above, we saved the result to a new variable each\n",
    "time (`poly_ref`, `poly_ref2`, and `poly_ref3`)?  You can use those variables to\n",
    "reposition the instances."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8",
   "metadata": {},
   "outputs": [],
   "source": [
    "poly_ref2.rotate(90)  # Rotate the 2nd instance we made by 90 degrees.\n",
    "poly_ref3.rotate(180)  # Rotate the 3rd instance we made by 180 degrees.\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9",
   "metadata": {},
   "source": [
    "Now you are getting somewhere! You have only had to make the polygon once, but you are\n",
    "able to reuse it as many times as you want.\n",
    "\n",
    "## Modifying the instance\n",
    "\n",
    "What happens when you change the original geometry that the reference points to?  In your case, your references in\n",
    "`c` all point to the Component `p` that with the original polygon.  Let us try\n",
    "adding a second polygon to `p`.\n",
    "\n",
    "First you add the second polygon and make sure `P` looks like you expect:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Add a 2nd polygon to \"p\".\n",
    "xpts = [14, 14, 16, 16]\n",
    "ypts = [0, 2, 2, 0]\n",
    "p.add_polygon(list(zip(xpts, ypts)), layer=(1, 0))\n",
    "p"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "11",
   "metadata": {},
   "source": [
    "That looks good.  Now let us find out what happened to `c` that contains the\n",
    "three references.  Keep in mind that you have not modified `c` or executed any\n",
    "functions/operations on `c` -- all you have done is modify `p`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13",
   "metadata": {},
   "source": [
    " **When you modify the original geometry, all of the\n",
    "references automatically reflect the modifications.**  This is very powerful,\n",
    "because you can use this to make very complicated designs from relatively simple\n",
    "elements in a computation- and memory-efficient way.\n",
    "\n",
    "Let us try making references a level deeper by referencing `c`.  Note here we use\n",
    "the `<<` operator to add the references -- this is just shorthand, and is\n",
    "exactly equivalent to using `add_ref()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "14",
   "metadata": {},
   "outputs": [],
   "source": [
    "c2 = gf.Component()\n",
    "d_ref1 = c2.add_ref(c)  # Reference the Component \"c\" that 3 references in it.\n",
    "d_ref2 = c2 << c  # Use the \"<<\" operator to create a 2nd reference to c.plot().\n",
    "d_ref3 = c2 << c \n",
    "\n",
    "d_ref1.move((20, 0))\n",
    "d_ref2.move((40, 0))\n",
    "\n",
    "c2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "15",
   "metadata": {},
   "source": [
    "As you have seen you have two ways to add a reference to our component:\n",
    "\n",
    "1. Create the reference and add it to the component"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "wr = c.add_ref(gf.components.straight(width=0.6))\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17",
   "metadata": {},
   "source": [
    "2. Or do it in a single line"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "wr = c << gf.components.straight(width=0.6)\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "19",
   "metadata": {},
   "source": [
    "In both cases you can move the reference `wr` after created"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "wr1 = c << gf.components.straight(width=0.6)\n",
    "wr2 = c << gf.components.straight(width=0.6)\n",
    "wr2.movey(10)\n",
    "\n",
    "# This takes the ports from the bottom waveguide (wr1), which are named o1 and o2, and adds them to c with the prefix \"bot_\".\n",
    "# The new ports on c will be named bot_o1 and bot_o2.\n",
    "c.add_ports(wr1.ports, prefix=\"bot_\")\n",
    "\n",
    "# This does the same for the upper waveguide (wr2), creating 2 new ports on c named top_o1 and top_o2.\n",
    "c.add_ports(wr2.ports, prefix=\"top_\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "21",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.pprint_ports()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22",
   "metadata": {},
   "source": [
    "You can also auto_rename ports using gdsfactory default convention, where ports are numbered clockwise starting from the bottom left."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "23",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.auto_rename_ports()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "24",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.pprint_ports()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "25",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "26",
   "metadata": {},
   "source": [
    "## Arrays of Instances\n",
    "\n",
    "In GDS, there's a type of structure called an \"Instance\" which takes a cell and repeats it NxM times on a fixed grid spacing. For convenience, `Component` includes this functionality with the add_ref() function.\n",
    "\n",
    "\n",
    "Let's make a new Component and put a big array of our Component `c` in it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "c3 = gf.Component() \n",
    "c = gf.components.straight(length=1)\n",
    "\n",
    "# This is the key step where the array is created.\n",
    "# The add_ref function is used to place the unit cell c into the main component c3, but with additional parameters to create a grid:\n",
    "# columns=2, rows=2: This specifies a 2x2 grid.\n",
    "# column_pitch=10: The horizontal distance between the centers of adjacent columns is 10 µm.\n",
    "# row_pitch=20: The vertical distance between the centers of adjacent rows is 20 µm.\n",
    "# The variable aref holds a reference to this entire array.\n",
    "aref = c3.add_ref(c, columns=2, rows=2, column_pitch=10, row_pitch=20)  \n",
    "c3.add_ports(aref.ports) # The ports are then automatically named to indicate the position in the array (o1_0_0, o2_0_0, o1_1_0, o2_1_0, etc.).\n",
    "\n",
    "# Reference the Component \"c\" 4 references in it with a 2 rows, 2 columns array.\n",
    "c3.pprint_ports()\n",
    "c3.draw_ports()\n",
    "c3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28",
   "metadata": {},
   "outputs": [],
   "source": [
    "aref['o1', 1, 1].x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29",
   "metadata": {},
   "outputs": [],
   "source": [
    "aref.ports['o1', 0, 0].x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30",
   "metadata": {},
   "outputs": [],
   "source": [
    "len(aref.ports)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31",
   "metadata": {},
   "source": [
    "You can access the port from the array. Where (0, 0) is the bottom left instance in the array."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "32",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "b = c << gf.components.bend_euler()\n",
    "s = c.add_ref(\n",
    "    gf.components.straight(length=1),\n",
    "    rows=2,\n",
    "    row_pitch=10,\n",
    "    columns=2,\n",
    "    column_pitch=10,\n",
    ")\n",
    "b.connect(\"o1\", s[\"o2\", 1, 1])\n",
    "c"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33",
   "metadata": {},
   "source": [
    "gdsfactory provides you with similar functionality in `gf.components.array`. Notice that the port naming is different!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "34",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "c4 = gf.Component()\n",
    "c = gf.components.straight(length=1)\n",
    "aref = c4 << gf.components.array(component=c, columns=2, rows=2, row_pitch=10, column_pitch=10)\n",
    "c4.add_ports(aref.ports)\n",
    "c4.pprint_ports()\n",
    "c4.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "help(gf.components.array)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "source": [
    "You can also create an array of references for periodic structures. Let us create a [Distributed Bragg Reflector](https://picwriter.readthedocs.io/en/latest/components/dbr.html).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37",
   "metadata": {},
   "outputs": [],
   "source": [
    "@gf.cell\n",
    "def dbr_period(w1=0.5, w2=0.6, l1=0.2, l2=0.4, straight=gf.components.straight):\n",
    "    \"\"\"Return one DBR period.\"\"\"\n",
    "    c = gf.Component()\n",
    "    r1 = c << straight(length=l1, width=w1)\n",
    "    r2 = c << straight(length=l2, width=w2)\n",
    "\n",
    "    # The second waveguide (r2) is automatically moved to connect its input port (o1) to the output port of the first waveguide (r1.ports[\"o2\"]).\n",
    "    # The allow_width_mismatch=True is necessary because the two waveguides have different widths.\n",
    "    r2.connect(port=\"o1\", other=r1.ports[\"o2\"], allow_width_mismatch=True)\n",
    "    \n",
    "    # The unconnected input of the first section and the unconnected output of the second section are \"exported\".\n",
    "    # These will become the ports of the main dbr_period component.\n",
    "    c.add_port(\"o1\", port=r1.ports[\"o1\"])\n",
    "    c.add_port(\"o2\", port=r2.ports[\"o2\"])\n",
    "    return c\n",
    "\n",
    "\n",
    "l1 = 0.2\n",
    "l2 = 0.4\n",
    "n = 3\n",
    "period = dbr_period(l1=l1, l2=l2)\n",
    "period"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38",
   "metadata": {},
   "outputs": [],
   "source": [
    "# period: The component to be repeated.\n",
    "# columns=n: Creates n copies in the horizontal direction (since n was set to 3, it creates 3 copies).\n",
    "# rows=1: Creates a single row.\n",
    "# column_pitch=l1 + l2: This sets the horizontal distance between the start of each repeated period. \n",
    "# By setting it to the total length of one period (l1 + l2), the copies are placed perfectly end-to-end, creating a continuous structure.\n",
    "\n",
    "dbr = gf.Component()\n",
    "dbr.add_ref(period, columns=n, rows=1, column_pitch=l1 + l2)\n",
    "dbr"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39",
   "metadata": {},
   "source": [
    "Finally we need to add ports to the new component."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "40",
   "metadata": {},
   "outputs": [],
   "source": [
    "# This adds two ports, o1 and o2, to the dbr component. However, it uses the ports from the single period component as a template. This means that initially:\n",
    "# Port o1 is correctly placed at the start (0, 0).\n",
    "# Port o2 is incorrectly placed at the end of the first period, not at the end of the whole 3-period structure.\n",
    "\n",
    "p0 = dbr.add_port(\"o1\", port=period.ports[\"o1\"])\n",
    "p1 = dbr.add_port(\"o2\", port=period.ports[\"o2\"])\n",
    "\n",
    "# The crucial step that corrects the position of the output port (p1).\n",
    "# (l1 + l2) * n: This calculates the total length of the DBR (the length of one period multiplied by the number of periods, n=3).\n",
    "# By setting p1.dcenter to this new coordinate, the output port is moved to the very end of the final DBR structure.\n",
    "\n",
    "p1.dcenter = ((l1 + l2) * n, 0)\n",
    "dbr.draw_ports()\n",
    "dbr"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41",
   "metadata": {},
   "source": [
    "## Connect references\n",
    "\n",
    "We have seen that once you create a reference you can manipulate the reference to move it to a location. Here we are going to connect that reference to a port. Remember that we follow that a certain reference `source` connects to a `destination` port."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "42",
   "metadata": {},
   "outputs": [],
   "source": [
    "bend = gf.components.bend_circular()\n",
    "bend"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "\n",
    "mmi = c << gf.components.mmi1x2()\n",
    "b = c << gf.components.bend_circular()\n",
    "b.connect(\"o1\", other=mmi.ports[\"o2\"])\n",
    "\n",
    "c.add_port(\"o1\", port=mmi.ports[\"o1\"])\n",
    "c.add_port(\"o2\", port=b.ports[\"o2\"])\n",
    "c.add_port(\"o3\", port=mmi.ports[\"o3\"])\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44",
   "metadata": {},
   "source": [
    "You can also access the ports as `reference[port_name]` instead of `reference.ports[port_name]`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "45",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "\n",
    "mmi = c << gf.components.mmi1x2()\n",
    "b = c << gf.components.bend_circular()\n",
    "b.connect(\"o1\", other=mmi[\"o2\"])\n",
    "\n",
    "#The unconnected ports of the sub-components are \"exported\" to become the ports of the main component c.\n",
    "# c.add_port(\"o1\", ...): The main input is the MMI's input port.\n",
    "# c.add_port(\"o2\", ...): The first main output is the bend's output port.\n",
    "# c.add_port(\"o3\", ...): The second main output is the MMI's other, still unconnected, output port (mmi[\"o3\"]).\n",
    "c.add_port(\"o1\", port=mmi[\"o1\"])\n",
    "c.add_port(\"o2\", port=b[\"o2\"])\n",
    "c.add_port(\"o3\", port=mmi[\"o3\"])\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "46",
   "metadata": {},
   "source": [
    "Notice that `connect` merges two ports together and does not imply that ports will remain connected.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47",
   "metadata": {},
   "source": [
    "## Accessing parent cell from instances\n",
    "\n",
    "You can access the cell from the instance."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(b.cell.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "49",
   "metadata": {},
   "source": [
    "## Accessing components from layout\n",
    "\n",
    "You can also access the Component from the layout by the Component name. You can access the cells from the KCLayout:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50",
   "metadata": {},
   "outputs": [],
   "source": [
    "bend = c.kcl[b.cell.name]\n",
    "print(type(bend))\n",
    "bend"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "51",
   "metadata": {},
   "source": [
    "## Port\n",
    "\n",
    "You can assign custom names to ports and later rename them using `gf.port.auto_rename_ports(prefix='o')` or `component.auto_rename_ports()` which will rename them in place.\n",
    "\n",
    "By default, ports are numbered clockwise starting from the bottom-left corner. The naming conventions are:\n",
    "\n",
    "- Optical ports use the prefix o.\n",
    "- Electrical ports use the prefix e.\n",
    "\n",
    "\n",
    "Here is the default one we use (clockwise starting from bottom left corner):\n",
    "\n",
    "```\n",
    "             3   4\n",
    "             |___|_\n",
    "         2 -|      |- 5\n",
    "            |      |\n",
    "         1 -|______|- 6\n",
    "             |   |\n",
    "             8   7\n",
    "```\n",
    "\n",
    "Port names are defined in the gdsfactory.cross_section. For example:\n",
    "\n",
    "- gdsfactory.cross_section.strip assigns `o1` for the input and `o2` for the output.\n",
    "- gdsfactory.cross_section.metal1 assigns `e1` for the input and `e2` for the output.\n",
    "\n",
    "Here are the most commonly used port types:\n",
    "\n",
    "\n",
    "| Port Type       | Description                                      |\n",
    "|-----------------|--------------------------------------------------|\n",
    "| optical         | Optical ports                                    |\n",
    "| electrical      | Electrical ports                                 |\n",
    "| placement       | Placement ports (excluded in netlist extraction) |\n",
    "| vertical_te     | For grating couplers with TE polarization         |\n",
    "| vertical_tm     | For grating couplers with TM polarization         |\n",
    "| electrical_rf   | Electrical ports for RF (high frequency)          |\n",
    "| pad             | For pads                                          |\n",
    "| pad_rf          | For RF pads                                       |\n",
    "| bump            | For bumps                                         |\n",
    "| edge_coupler    | For edge couplers                                 |\n",
    "\n",
    "\n",
    "If you want to define another type that is not included you can do it like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "52",
   "metadata": {},
   "outputs": [],
   "source": [
    "gf.CONF.port_types += [\"my_own_port_type\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "53",
   "metadata": {},
   "outputs": [],
   "source": [
    "size = 4\n",
    "\n",
    "# The gf.components.nxn function is a convenient tool for creating a rectangular component with a specified number of ports on each side.\n",
    "c = gf.components.nxn(west=2, south=2, north=2, east=2, xsize=size, ysize=size)\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "54",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.pprint_ports()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55",
   "metadata": {},
   "source": [
    "You can get the optical ports by `layer`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "56",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.get_ports_list(layer=(1, 0))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "57",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.pprint_ports(layer=(1, 0))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "58",
   "metadata": {},
   "source": [
    "or by `width`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.get_ports_list(width=500)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "60",
   "metadata": {},
   "outputs": [],
   "source": [
    "# A straight_heater_metal component is created. \n",
    "# This is a complex component that has both optical ports for the waveguide and electrical ports for the metal heater.\n",
    "c0 = gf.components.straight_heater_metal()\n",
    "c0.pprint_ports() # This command prints a neatly formatted table of the ports on the original component, c0. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61",
   "metadata": {},
   "outputs": [],
   "source": [
    "c1 = c0.dup() # A duplicate of the component is created and stored in c1. Then, the auto_rename_ports() function is called on this new component.\n",
    "c1.auto_rename_ports()\n",
    "c1.pprint_ports()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62",
   "metadata": {},
   "source": [
    "You can also rename them with a different port naming convention:\n",
    "\n",
    "- Prefix: add `e` for electrical `o` for optical\n",
    "- Clockwise\n",
    "- Counter-clockwise\n",
    "- Orientation `E` East, `W` West, `N` North, `S` South\n",
    "- Note: All ports are east facing by default and need to be rotated in order to have a different orientation.\n",
    "\n",
    "Here is the default one we use (clockwise starting from bottom left west facing port):\n",
    "\n",
    "```\n",
    "             3   4\n",
    "             |___|_\n",
    "         2 -|      |- 5\n",
    "            |      |\n",
    "         1 -|______|- 6\n",
    "             |   |\n",
    "             8   7\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "63",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component(\"demo_ports\")\n",
    "nxn = gf.components.nxn(west=2, north=2, east=2, south=2, xsize=4, ysize=4)\n",
    "ref = c.add_ref(nxn)\n",
    "c.add_ports(ref.ports)\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64",
   "metadata": {},
   "outputs": [],
   "source": [
    "gf.port.pprint_ports(ref.ports)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "65",
   "metadata": {},
   "source": [
    "You can also get the ports counter-clockwise:\n",
    "\n",
    "```\n",
    "             4   3\n",
    "             |___|_\n",
    "         5 -|      |- 2\n",
    "            |      |\n",
    "         6 -|______|- 1\n",
    "             |   |\n",
    "             7   8\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.get_ports_list(clockwise=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67",
   "metadata": {},
   "source": [
    "Lets extend the east facing ports (orientation = 0 deg):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "# This defines a standard strip waveguide cross-section, which contains information about the waveguide's width, layer, and other properties.\n",
    "# A strip waveguide has a core with material which has a high refractive index, whereas the cladding (material surrounding the core) has a low refractive index.\n",
    "# This contrast leads to the strip being able to confine light very tightly, thus allowing for sharp bends with minimal loss of light.\n",
    "cross_section = gf.cross_section.strip()\n",
    "\n",
    "# A 4x4 square component with two ports on each side is created. \n",
    "# The cross_section parameter ensures that all the ports on this component are defined as strip waveguides.\n",
    "nxn = gf.components.nxn(\n",
    "    west=2, north=2, east=2, south=2, xsize=4, ysize=4, cross_section=cross_section)\n",
    "\n",
    "# The extend_ports function takes the nxn component and adds straight extensions to some of its ports.\n",
    "# component=nxn: The component to modify.\n",
    "# orientation=0: This tells the function to only add extensions to the ports that have an orientation of 0 degrees, \n",
    "# which corresponds to the ports on the east (right) side of the component.\n",
    "c = gf.components.extension.extend_ports(component=nxn, orientation=0)\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69",
   "metadata": {},
   "outputs": [],
   "source": [
    "c.pprint_ports()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "70",
   "metadata": {},
   "source": [
    "## Port markers (Pins)\n",
    "\n",
    "You can add pins (port markers) to each port. Different foundries do this differently, so gdsfactory supports all of them.\n",
    "\n",
    "- Square with port inside the component.\n",
    "- Square centered (half inside, half outside component).\n",
    "- Triangular pointing towards the outside of the port.\n",
    "- Path (SiEPIC).\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.components.mmi1x2()\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.components.mmi1x2()\n",
    "\n",
    "# The add_pins_container function takes the mmi component and returns a new component that includes the original MMI geometry plus visual annotations for each port. \n",
    "# These \"pins\" are typically short path markers and text labels showing the port's name (e.g., \"o1\"), making them easy to identify visually.\n",
    "c_with_pins = gf.add_pins.add_pins_container(c)\n",
    "\n",
    "# The plot will show the MMI component with a pin and a text label sticking out from each of its three ports, clearly indicating their location and name.\n",
    "# This is a useful utility for debugging and inspecting component layouts.\n",
    "c_with_pins.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "73",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.components.mmi1x2()\n",
    "c.draw_ports()\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74",
   "metadata": {},
   "source": [
    "## Component_sequence\n",
    "\n",
    "When you have repetitive connections you can describe the connectivity as an ASCII map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "75",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "# This creates a 180-degree circular bend, which is a U-shaped waveguide used to turn the path of light around completely.\n",
    "bend180 = gf.components.bend_circular180() \n",
    "\n",
    "# The following function creates a straight waveguide with PIN junctions and heaters. It includes the central silicon waveguide, \n",
    "# doped regions (positive and negative), and metal contacts for applying a voltage, often used for thermal tuning or modulation.\n",
    "# The straight_pin component is designed to be thermo-optic phase shifter, not just a simple waveguide.\n",
    "# A thermo-optic phase shifter is a device on a photonic chip that uses heat to control the phase of a light wave.\n",
    "wg_pin = gf.components.straight_pin(length=40)\n",
    "\n",
    "# This creates a simple, standard straight waveguide, which is the most basic component for guiding light in a straight line.\n",
    "wg = gf.components.straight()\n",
    "\n",
    "# Define a map between symbols and (component, input port, output port).\n",
    "symbol_to_component = {\n",
    "    \"D\": (bend180, \"o1\", \"o2\"),\n",
    "    \"C\": (bend180, \"o2\", \"o1\"),\n",
    "    \"P\": (wg_pin, \"o1\", \"o2\"),\n",
    "    \"-\": (wg, \"o1\", \"o2\"),\n",
    "}\n",
    "\n",
    "# Generate a sequence.\n",
    "# This is simply a chain of characters. Each of them represents a component.\n",
    "# with a given input and and a given output.\n",
    "\n",
    "sequence = \"DC-P-P-P-P-CD\"\n",
    "component = gf.components.component_sequence(\n",
    "\n",
    "    # The symbol_to_component is a Python dictionary that acts as a key, mapping the symbols from the sequence string to actual gdsfactory components.\n",
    "    sequence=sequence, symbol_to_component=symbol_to_component)\n",
    "component.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "76",
   "metadata": {},
   "source": [
    "As the sequence is defined as a string you can use the string operations to easily build complex sequences"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77",
   "metadata": {},
   "source": [
    "## Movement\n",
    "\n",
    "You can move, rotate and mirror Instance as well as `Port`, `Polygon`, `Instance`, `Label`, and `Group`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "# Start with a blank Component.\n",
    "c = gf.Component()\n",
    "\n",
    "# Create some more Components with shapes.\n",
    "T = gf.components.text(\"hello\", size=10, layer=(1, 0))\n",
    "E = gf.components.ellipse(radii=(10, 5), layer=(2, 0))\n",
    "R = gf.components.rectangle(size=(10, 3), layer=(3, 0))\n",
    "\n",
    "# Add the shapes to c as instances.\n",
    "text = c << T\n",
    "ellipse = c << E\n",
    "rect1 = c << R\n",
    "rect2 = c << R\n",
    "\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "e1 = c << gf.components.ellipse(radii=(10, 5), layer=(2, 0))\n",
    "e2 = c << gf.components.ellipse(radii=(10, 5), layer=(2, 0))\n",
    "e1.movex(10)\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "e1 = c << gf.components.ellipse(radii=(10, 5), layer=(2, 0))\n",
    "e2 = c << gf.components.ellipse(radii=(10, 5), layer=(2, 0))\n",
    "\n",
    "# This moves the second ellipse (e2) horizontally until its leftmost point (xmin) is perfectly aligned with the rightmost point (xmax) of the first ellipse (e1).\n",
    "e2.xmin = e1.xmax\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "81",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# Now you can practice move and rotate the objects.\n",
    "\n",
    "c = gf.Component()\n",
    "E = gf.components.ellipse(radii=(10, 5), layer=(2, 0))\n",
    "e1 = c << E\n",
    "e2 = c << E\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "e = gf.components.ellipse(radii=(10, 5), layer=(2, 0))\n",
    "e1 = c << e\n",
    "e2 = c << e\n",
    "e2.move((5, 5))  # Translate by dx = 5, dy = 5\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "83",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "r = gf.components.rectangle(size=(10, 5), layer=(2, 0))\n",
    "rect1 = c << r\n",
    "rect2 = c << r\n",
    "\n",
    "rect1.rotate(45)  # Rotate the first straight by 45 degrees around (0,0).\n",
    "rect2.rotate(-30)  # Rotate the second straight by -30 degrees around (1,1).\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "84",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "import gdsfactory as gf\n",
    "\n",
    "c = gf.Component()\n",
    "text = c << gf.components.text(\"hello\")\n",
    "text.dmirror(p1=(1, 1), p2=(1, 3))  \n",
    "# Reflects across the line formed by p1 and p2.\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "85",
   "metadata": {},
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "text = c << gf.components.text(\"hello\")\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86",
   "metadata": {},
   "source": [
    "Each Component and Instance object has several properties which can be used\n",
    "to learn information about the object (for instance where it's center coordinate\n",
    "is).  Several of these properties can actually be used to move the geometry by\n",
    "assigning them new values.\n",
    "\n",
    "Available properties are:\n",
    "\n",
    "- `xmin` / `xmax`: minimum and maximum x-values of all points within the object\n",
    "- `ymin` / `ymax`: minimum and maximum y-values of all points within the object\n",
    "- `x`: centerpoint between minimum and maximum x-values of all points within the\n",
    "object\n",
    "- `y`: centerpoint between minimum and maximum y-values of all points within the\n",
    "object\n",
    "- `bbox`: bounding box (see note below) in format ((xmin,ymin),(xmax,ymax))\n",
    "- `center`: center of bounding box"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\n",
    "    \"printing the bounding box of text in terms of [(xmin, ymin), (xmax, ymax)] in um\"\n",
    ")\n",
    "print(text.dbbox())  # In Decimal um (float).\n",
    "print(\"xsize and ysize:\")\n",
    "print(text.xsize)  # Will print the width of text in the x dimension in um\n",
    "print(text.ysize)  # Will print the height of text in the y dimension in um\n",
    "\n",
    "print(\"center:\")\n",
    "print(text.dcenter)  # Gives you the center coordinate of its bounding box in DBU\n",
    "print(\"xmax\")\n",
    "print(text.xmax)  # Gives you the rightmost (+x) edge of the text bounding box"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "text = c << gf.components.text(\"hello\")\n",
    "E = gf.components.ellipse(radii=(10, 5), layer=(3, 0))\n",
    "R = gf.components.rectangle(size=(10, 5), layer=(2, 0))\n",
    "rect1 = c << R\n",
    "rect2 = c << R\n",
    "ellipse = c << E\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "ellipse.dcenter = (0, 0)  # Move the ellipse to the center of the bounding box.\n",
    "\n",
    "# Next, let us move the text to the left edge of the ellipse.\n",
    "text.y = (\n",
    "    ellipse.y\n",
    ")  # Move the text so that its y-center is equal to the y-center of the ellipse.\n",
    "text.xmax = ellipse.xmin  # Moves the ellipse so its xmax == the ellipse's xmin.\n",
    "\n",
    "# Align the right edge of the rectangles with the x=0 axis.\n",
    "rect1.xmax = 0\n",
    "rect2.xmax = 0\n",
    "\n",
    "# Move the rectangles above and below the ellipse.\n",
    "rect1.ymin = ellipse.ymax + 5\n",
    "rect2.ymax = ellipse.ymin - 5\n",
    "\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90",
   "metadata": {},
   "outputs": [],
   "source": [
    "import gdsfactory as gf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# A bounding box is the smallest enclosing box which contains all points of the geometry.\n",
    "\n",
    "c = gf.Component()\n",
    "text = c << gf.components.text(\"hi\")\n",
    "c << gf.components.bbox(text, layer=(2, 0))\n",
    "fig = c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "text = c << gf.components.text(\"bye\")\n",
    "device_bbox = text.bbox\n",
    "\n",
    "# The gf.get_padding_points function takes the text component as input and calculates the vertices of a new polygon that surrounds it.\n",
    "# default=1: This specifies a uniform padding of 1 µm on all sides.\n",
    "# The resulting list of points is then used to add a new polygon to the component c on a different layer, (2, 0).\n",
    "c.add_polygon(gf.get_padding_points(text, default=1), layer=(2, 0))\n",
    "c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93",
   "metadata": {},
   "outputs": [],
   "source": [
    "# When we query the properties of c, they will be calculated with respect to this bounding-rectangle.  For instance:\n",
    "\n",
    "print(\"Center of Component c:\")\n",
    "print(c.dcenter)\n",
    "\n",
    "print(\"X-max of Component c:\")\n",
    "print(c.xmax)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "c = gf.Component()\n",
    "R = gf.components.rectangle(size=(10, 3), layer=(2, 0))\n",
    "rect1 = c << R\n",
    "f = c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95",
   "metadata": {
    "lines_to_next_cell": 2
   },
   "outputs": [],
   "source": [
    "# You can chain many of the movement/manipulation functions because they all return the object they manipulate.\n",
    "# For instance you can combine two expressions:\n",
    "\n",
    "rect1.rotate(angle=37)\n",
    "rect1.move((10, 20))\n",
    "f = c.plot()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ...into this single-line expression:\n",
    "\n",
    "c = gf.Component()\n",
    "R = gf.components.rectangle(size=(10, 3), layer=(2, 0))\n",
    "rect1 = c << R\n",
    "rect1.rotate(angle=37).move((10, 20))\n",
    "f = c.plot()"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "custom_cell_magics": "kql"
  },
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
